package com.gui.provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gui.DTO.GiteeOAuther;
import com.gui.DTO.GiteeUser;
import lombok.Setter;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * GithubProvider
 *
 * @author guigu
 * @QQ 1170258867
 * @date 2020/5/26
 * @description
 */
@Component
@ConfigurationProperties(prefix = "gitee.value") //这个报错无伤大雅
public class GiteeProvider {

    /**
     * 这里必须有set方法
     */

    @Setter
    private String tokenUrl;
    @Setter
    private String grantType;
    @Setter
    private String clientId;
    @Setter
    private String clientsecret;
    @Setter
    private String redirectUri;

    //两种注入方式
//    @Value("${gitee.value.tokenUrl}")
//    private String test;

    public String getaccessToken(GiteeOAuther giteeOAuther){
//        System.out.println("tokenUrl"+tokenUrl);
//        System.out.println("test"+test);
        giteeOAuther.setGrant_type(grantType);
        giteeOAuther.setClient_id(clientId);
        giteeOAuther.setRedirect_uri(redirectUri);
        giteeOAuther.setClient_secret(clientsecret);

        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(giteeOAuther));
        Request request = new Request.Builder()
                .url(tokenUrl)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            string = (String) jsonObject.get("access_token");
//            System.out.println(string);
            return string;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public GiteeUser getUserJson(String accessToken){
        String string = null;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token="+accessToken)
                .build();
        try (Response response = client.newCall(request).execute()) {
            string = response.body().string();
//            System.out.println(string);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return JSON.parseObject(string,GiteeUser.class);
    }
}
